package com.lianliang.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import com.lianliang.domain.User;

@Repository
public class UserDao {
	@Autowired
	private JdbcTemplate jdbc;
	
	/*
	 * 根据用户名、密码匹配用户
	 * */
	public Integer getMatchCount(String userName,String password){
		String sql = "SELECT COUNT(u.user_id) FROM `t_user` u "+
					"WHERE u.`user_name`=? AND u.`password`=?";
		return jdbc.queryForInt(sql, userName, password);
	}
	/*
	 * 根据用户名查找对象
	 * */
	public User findUserByUserName(final String userName){
		String sql = "SELECT u.`user_id`,u.`user_name`,u.`credits` "+
					"FROM `t_user` u "+
					"WHERE u.`user_name`=?";
		final User user = new User();
		jdbc.query(sql, new Object[]{userName}, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				user.setUserId(rs.getInt("user_id"));
				user.setUserName(userName);
				user.setCredits(rs.getInt("credits"));
			}
		});
		return user;
	}
	/*
	 * 更新信息
	 * */
	public void updateLoginLog(User user){
		String sql = "UPDATE `t_user` u SET u.`credits`=?,u.`last_ip`=?,u.`last_visit`=? WHERE u.`user_id`=?";
		jdbc.update(sql, user.getCredits(),user.getLastIp(),user.getLastVisit(),user.getUserId());
	}
	
	
}
